<?php
class User_model extends MY_Model
{
	public
		$table = 'users',
		$prKey = 'user_ID',

		$status = array(			
			'1' => 'Active',
			'2' => 'Inactive',
			'3' => 'Blocked',
		),
        $acl_roles = array(
            '1'     => 'Superadmin',
            '2'     => 'Administrator',
            '3'     => 'User',
            '4'     => 'Journalist'
        );

	function __construct()
	{
       
		parent::__construct();



		$this->fields = array(
			'full_name'			=> T_('Full Name'),
			'friendemail'		=> T_('Friend Email'),
			'id'		 		=> '',
			'first_name'		=> T_('First Name'),
			'last_name'			=> T_('Last Name'),
			'nickname'			=> T_('Forum Name'),
			'email' 			=> T_('E-Mail'),
			'email_confirm'		=> T_('Confirm E-Mail'),		
			'password' 			=> T_('Password'),
			'new_password' 		=> T_('Password'),
			'password_confirm' 	=> T_('Confirm Password'),
			'payment_method' 	=> T_('Payment Method'),
			'acl_role' 			=> T_('Acl Role'),
            
            //payment_info.php
            'phone'  			=> T_('Phone Number'),
            'address'           => T_('Address'),
            'city'              => T_('City'),
            'country_ID'        => T_('Country'),
            'state_name'        => T_('State'),
            'zip_code'          => T_('Zip Code'),
            'card_type'         => T_('Card Type'),
            'card_number'       => T_('Card Number'),
            'exp_date'          => T_('Exp Date'),
            'exp_month'         => T_('Exp Month'),
            'exp_year'          => T_('Exp Year'),
            'security_code'     => T_('Security Code'),
		
			//post_request.php
			
			'member_id'     		=> T_('Member ID'),
			'referral_no'			=> T_('Referral No'),
			'referral_abstract'     => T_('Referral Abstract'),
			'referral_details'		=> T_('Referral Details'),
			'end_date'     			=> T_('End Date'),
			'ask_price'				=> T_('Ask Price'),
			'status'     			=> T_('Status'),
			'date_posted'			=> T_('Date Posted'),
            'province'              => T_('Province'),

            //connect_with_bidder

            'sender_id'         => T_('Member ID'),
            'status'            => T_('Status'),
            'date_posted'       => T_('Date Posted'),
            'bid_price'         => T_('Bid Price'),
            'receiver_id'       => T_('Member ID'),
            'message_header'    => T_('Message Header'),
            'message_text'      => T_('Message Text'),
		
		
			//accept_bid
			
			'bidder_id'    		=> T_('Bidder ID'),
            'accepted_bid'      => T_('Accepted Bid'),

            //profile_referral

			'full_name'    		=> T_('Full Name'),
            'friendemail'      => T_('E-Mail'),

            //choice

            'user_type'         => T_('User_type'),
            'bred'              => T_('bred'),
            //email_verification

            'verify'      => T_('VERIFY'),
            'resend'      => T_('RESEND'),
            'verify_input'      =>T_('Verification'),
            'resend_input'      =>T_('Resending'),

            //bids

            'ref_status'        => 'Status',
            'ref_date_posted'   => 'Date Posted',
            'ref_end_date'      => 'End Date',
            'ref_abstract'      => 'Description',
            'ref_ask'           => 'Ask',
            'ref_bids'          => '# Bids',
            'ref_avg_bid'       => 'Avg. Bid',

            'bid_no'            => 'Bid No.',
            'bid_date'          => 'Bid Date',
            'member_id'         => 'Member ID',
            'response_ex'       => 'Response Excerpt',
            'bid_price'         => 'Bid',

			//captcha
			'captcha_id' 		=> T_('ID Captcha'),
			'captcha_code' 		=> T_('Code verification'),
		);
		
/*
 * 
		$this->fields = array(
			'id'		 		=> '',
			'fullname' 			=> T_('Ф�?О'),
			'email' 			=> T_('E-mail'),
			'password' 			=> T_('Пароль'),
			'new_password' 		=> T_('Пароль'),
			'password_confirm' 	=> T_('Пароль еще раз'),
			'phone' 			=> T_('Номер телефона'),
			'ani'				=> T_('Номер телефона'),
			'id_countries' 		=> T_('Страна'),
			'id_states' 		=> T_('Область'),
			'id_cities' 		=> T_('Город'),
			'id_districts' 		=> T_('Район города'),
			'street' 			=> T_('Улица'),
			'birth'			 	=> T_('День рождения'),
			'social_status'		=> T_('Социальное положение'),
			'income'			=> T_('Уровень дохода'),
			'family'		 	=> T_('Семейное положение'),
			'gender' 			=> T_('Пол пользователя'),		
			'status' 			=> T_('Статус'),
			'balance' 			=> T_('Лицевой счет'),
			'date_created' 		=> T_('Дата создания'),	
			'activation_code' 	=> T_('Хеш-строка активации аккаунта'),
			'with_sms'		 	=> T_('Получение дополнительной информации через SMS'),
			'with_email'		=> T_('Получение дополнительной информации по e-mail'),
			'with_destination' 	=> T_('Автоматическое определение моего местонахождения в момент прослушивания рекламы.'),
		    'forgot_user_login' => T_('E-mail'),			
		);
*/			
		$this->rules = array(
					
			'first_name'		=> "trim|required|max_length[255]",
			'last_name'			=> "trim|required|max_length[255]",
			'nickname'			=> "trim|required|max_length[64]",
			'email' 			=> "trim|required|valid_email|max_length[64]|callback___loginFree",
			'friendemail'		=> "trim|required|valid_email|max_length[64]",	
			'email_confirm' 	=> "trim|matches[email_confirm]|required|valid_email|max_length[64]",
			'password' 			=> "trim|required|matches[password_confirm]|min_length[5]|max_length[64]|callback___correct_pass",
			'new_password' 		=> "trim|[password_confirm]|min_length[8]|max_length[64]|callback___correct_pass",			
			'password_confirm' 	=> "trim|min_length[8]|max_length[64]",	
			'payment_method' 	=> "trim|is_natural_no_zero",
			'acl_role'          => "trim|required|is_natural_no_zero",
			
            //paynment_info
            'phone'				=> "trim|required|max_length[255]",
            'exp_month'         => "trim|required|is_natural_no_zero",
            'exp_year'          => "trim|required|is_natural_no_zero",
            'address'           => "trim|required|max_length[255]",
            'city'              => "trim|required|max_length[255]",
            'country_ID'        => "trim|required|is_natural_no_zero",
            'state_ID'          => "trim|is_natural_no_zero",
            'province'          => "trim|max_length[255]",
            'zip_code'          => "trim|required|max_length[255]",
            'card_type'         => "trim|required|max_length[255]",
            'card_number'       => "trim|required|max_length[255]",
            'security_code'     => "trim|required|max_length[255]",
            //email_verification
            'verify_input'      => "trim|required|max_length[255]",
            'resend_input'      => "trim|required|valid_email|max_length[255]",
            //
			'member_id'     		=> "trim|required|max_length[255]",
			'referral_no'			=> "trim|required|max_length[255]",
			'referral_abstract'     => "trim|required|max_length[255]",
			'referral_details'		=> "trim|max_length[255]",
			'end_date'     			=> "trim|required|max_length[255]",
			'ask_price'				=> "trim|required|max_length[255]",
			'status'     			=> "trim|required|max_length[255]",
			'date_posted'			=> "trim|required|max_length[255]",
           
            //connect_with_bidder
            'sender_id'         => "trim|required|max_length[255]",
            'status'            => "trim|required|is_natural_no_zero|max_length[255]",
            'referral_no'       => "trim|required|max_length[255]",
            'date_posted'       => "trim|required|max_length[255]",
            'referral_abstract' => "trim|required|max_length[255]",
            'bid_price'         => "trim|required|max_length[255]",
            'receiver_id'       => "trim|required|max_length[255]",
            'message_header'    => "trim|required|max_length[255]",
            'message_text'      => "trim|required|max_length[255]",
		   //profile_referral
            'full_name'         => "trim|required|required|max_length[255]",
            'friendemail'       => "trim|required|valid_email|max_length[64]",
			
            //accept_bid
            
            'bidder_id'    		=> "trim|required|max_length[255]",
            'accepted_bid'      => "trim|required|max_length[255]",

			'captcha_id' 		=> "trim|required",
			'captcha_code' 		=> "trim|required|callback___captcha",
		);
	}
  function getProfileData($id = null) {
	if(!empty($id)) {
		$this->db->where('user_id', $id);
		$data = $this->db->get($this->table);
		
		return $data->row_array();
	}
  } 		
  function loginFree($login = null)
  {
  	$this->db->where('user_email', $login);

   	$this->user_ID = 1;
    if(!empty($this->user_ID))
    {

      $this->db->where('user_ID !=', $this->user_ID); 
    }
    
    $query = $this->db->get($this->table);

    if (!$query->num_rows())
    {
      return true;
    }   
    
    return false;
  }
  
  function correct_pass($str){
        $capital_letter = FALSE;
  	$numbers = FALSE;
  	$arr1 = str_split($str);
  	
  	 for ($i=0; $i < count($arr1); $i++){
  		 if(ctype_upper($arr1[$i])){  		 
  		 	$capital_letter  = TRUE;  			  			 
  			break;  			
  		 }
  	 }
	 for ($i=0; $i < count($arr1); $i++){
		 if(ctype_digit ($arr1[$i])){		 				 
			$numbers = TRUE; 
			break;  			
		 }
	 }
  	if($capital_letter  == TRUE && $numbers == TRUE){
  		return true;
  	}
  	
  	return false;
  }
  
  	function save($data)
	{
		if (isset($data['password']))
		{
			$data['password'] = $this->__cryptPassword($data['password']);
		}

		parent::save($data);
	}
		
	function __cryptPassword($password = null)
	{
		return md5($password . SALT);	
	}
	
	function getByLoginPassword($login = null, $password = null)
	{
		$sql = "
			SELECT u.user_id, u.user_email, u.user_first_name, u.user_created, u.user_status, u.user_id_acl_roles, r.name AS role
			FROM ".$this->table." u
			LEFT JOIN acl_roles r ON r.id=u.user_id_acl_roles
			WHERE u.user_email=".$this->db->escape($login)." AND u.user_password='".$this->__cryptPassword($password)."'";

		$query = $this->db->query($sql);

		if ($query->num_rows() > 0)
		{
			return $query->row_array();
		}
		
		return false;
	}
	
    function getByLogin($login = null)
    {
        $sql = "
            SELECT *
            FROM ".$this->table."
            WHERE user_email=".$this->db->escape($login);
        $user = $this->db->query($sql)->row_array();
        
        if (!empty($user))
        {
            return $user;
        }
        
        return false;
    }
	
	function search($config = array())
	{
            $id_user        = $this->input->get_post('user_ID');
            $name_first     = $this->input->get_post('user_first_name');
            $name_last      = $this->input->get_post('user_last_name');
            $email          = $this->input->get_post('user_email');
            $phone          = $this->input->get_post('user_phone');
            $date_start     = $this->input->get_post('user_date_created');
            $user_type      = $this->input->get_post('user_type');
            $user_status    = $this->input->get_post('user_status');

		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');

		// main sql
		$sql = '';
		$sql .= ' FROM '.$this->table.' u';
		$sql .= ' WHERE 1 = 1';

		if ($id_user)
		{
			$sql .= ' AND u.user_ID='.$this->db->escape($id_user);
		}

		if ($name_first)
		{
			$sql .= ' AND (u.user_first_name LIKE ' . $this->db->escape("%" . $name_first . "%") . ' OR u.user_first_name LIKE ' . $this->db->escape("%" . $name_first . "%") . ')';
		}
                if ($name_last)
		{
			$sql .= ' AND (u.user_last_name LIKE ' . $this->db->escape("%" . $name_last . "%") . ' OR u.user_first_name LIKE ' . $this->db->escape("%" . $name_last . "%") . ')';
		}

		if ($email)
		{
			$sql .= ' AND u.user_email='.$this->db->escape($email);
		}

		if ($phone)
		{
			$sql .= ' AND u.user_phone='.$this->db->escape($phone);
		}

		if ($date_start)
		{
			$sql .= ' AND u.user_created>='.$this->db->escape($date_start);
		}
	
    	if ($user_type)
		{
			$sql .= ' AND u.user_type>='.$this->db->escape($user_type);
		}
    	if ($user_status)
		{
			$sql .= ' AND u.user_status>='.$this->db->escape($user_status);
		}

		switch ($order)
		{
			case 'date':
				$sql .= ' ORDER BY u.date_created';
				break;

			default:
				$sql .= ' ORDER BY u.user_ID';
				$direction = 'DESC';
		}

		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';
        $sql = "SELECT * " . $sql;

        
		$this->data['list'] = $this->db->query($sql)->result();
        if(empty($this->data['list'])){
                $this->data['message_error'] = "Didn't exist in data base.";
        }

	}	

//gets notification  settings ids from db
  function getNotifications($userID){
       $sql = "SELECT *
               FROM users_notifications
               WHERE user_ID=".$userID;
        $result = $this->db->query($sql)->result_array();
        
        $notification_checked = array(0, 0, 0, 0, 0);

        foreach($result as $key => $value) {
            $notification_checked[$value['users_notification_ID']] = 1;
        }
        $this->data['notification_checked'] = $notification_checked;
        
        //input

      	$checked = array(0, 0, 0, 0, 0);
        if ($this->input->post('updateSettings')) {
        	for($i=0; $i<5; $i++)
                if($this->input->get_post('n'.$i) == 'accept')
        			$checked[$i] = 1;
        
        $this->data['notification_checked'] = $checked;
        $result = array_differ($notification_checked,$checked);


        if(!empty($result)) {
            $queryinsert = "";//"INSERT INTO users_notifications";// (column1, column2, column3) VALUES (�data1�, �data2�, �data3�);";
            $querydelete = "";//DELETE FROM users_notifications WHERE user_ID=6 AND users_notification_ID IN (1,3);
            foreach($result as $key => $value) {
                
                if($value == "1"){
                    if($queryinsert!=="") $queryinsert.=",";
                    $queryinsert.="('".$userID."','".$key."')";
                }else{
                    if($querydelete!=="") $querydelete.=",";
                    $querydelete.=$key;
                }
            }
            if($queryinsert!==""){
                $queryinsert="INSERT INTO users_notifications VALUES ".$queryinsert.";";
                $this->db->query($queryinsert);
            }
            if($querydelete!==""){
                $querydelete="DELETE FROM users_notifications WHERE user_ID=".$userID." AND users_notification_ID IN (".$querydelete.");";
                $this->db->query($querydelete);
            }
          }
        }
        return $result;
  }

  //checks if this code is written in db, changes user status according to it, erases code
  function verifyUserEmail($verification_code){

        $sql = "SELECT COUNT(*) AS number 
                FROM users
                WHERE user_verification_code=".$this->db->escape($verification_code);
        $result = $this->db->query($sql)->row_array();

        if($result['number'] > 0){
            $sql =  "UPDATE users SET user_status=1, user_verification_code='' WHERE user_verification_code=".$this->db->escape($verification_code)." AND user_status!=1";
            $this->db->query($sql);
            $isok = true;

        }else {
            $isok = false;
        }
      return $isok;
  }

  function get($id = null)
	{
		$this->db->from($this->table);
		$this->db->where('user_ID', $id);
		$query = $this->db->get();

		return $query->row_array();
	}

  function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);

		$error = "";
		$report = "";
		foreach ($items as $id)
		{
			$data = $this->user_model->get($id);

			$res = $this->db->delete($this->table, array($this->prKey => $id));
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Page was not removed.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$this->log->writeMessage('done', T_('Page was removed.'));
				$report .= ",1"; // deleted
			}
		}

		return substr($report, 1);
	}


  //inserts data from array into the fields named as indexes in array
  function insert($data)
  {
    if (!empty($data))
    {
      if (isset($data['user_password']))
      {
        $data['user_password'] = $this->__cryptPassword($data['user_password']);
      }
  
      $data['user_created'] = date('Y-m-d H:i:s');
      //$data['user_modified'] = date('Y-m-d H:i:s');     
      
      parent::insert($data);

      if ($this->db->insert_id() > 0)
      {
        $this->log->writeMessage('done', T_('User was successfully created.'));
/*        
        if ($this->config->item('base_url') == '/admin/')
		{
	        $log['id_admins'] = $this->auth->getID();
	        $log['message']   = T_('Слушатель <span class="green">'). $data['fullname'] . T_('</span> успешно добавлен.');        
	        $log['location']  = $_SERVER['REQUEST_URI'];
	        $this->watchdog_model->insert($log);
		}
*/		
        return TRUE;
      }
      else
      {
        $this->log->writeMessage('error', T_('Error! User was not created.'));
        
        return FALSE;
      }
    }   
  }

  function update($data) {
  	
    if (!empty($data))
    {
      if (isset($data['user_password']))
      {
        $data['user_password'] = $this->__cryptPassword($data['user_password']);
      }
  
      $data['user_modified'] = date('Y-m-d H:i:s');
        
      $res = parent::update($data);

      $this->log->writeMessage('done', T_('The data saved successfully.'));
		
      return TRUE;      
    }   
  } 
  
  	function activateUser($code = '')
	{
		if(empty($code)) return FALSE;
		
		$sql = "SELECT id FROM contributors WHERE activation_code=".$this->db->escape($code);
		$user = $this->db->query($sql)->row();
		
		if (!empty($user))
		{
			$sql = "UPDATE contributors SET status=".USER_STATUS_ACTIVE.", activation_code='' WHERE id=".$user->id;
			$this->db->query($sql);
			
			return TRUE;
		}
		else
		{
			$sql = "SELECT id FROM companies WHERE activation_code=".$this->db->escape($code);
			$user = $this->db->query($sql)->row();
		
			if (!empty($user))
			{
				$sql = "UPDATE companies SET status=".USER_STATUS_ACTIVE.", activation_code='' WHERE id=".$user->id;
				$this->db->query($sql);
				
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		}
	}
	
    function resetPasswordUser($code = '')
    {
        if(empty($code)) return FALSE;
        
        $sql = "SELECT id FROM ".$this->table." WHERE activation_code=".$this->db->escape($code);
        $user = $this->db->query($sql)->row();
        
        if (!empty($user))
        {
            $sql = "UPDATE ".$this->table." SET password=".$this->db->escape($code).", activation_code='' WHERE id=".$user->id;
            $this->db->query($sql);
            
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    //gets user information according to field
    function getUserField($field){
        $userID=$this->auth->getID();
    	$sql = "SELECT ".$field." 
    			FROM users
    			WHERE user_ID='".$userID."'";
        $result = $this->db->query($sql)->row_array();
        return $result;
    }
     function get_id(){
    $sql = "SELECT MAX(user_ID) AS number
            FROM ".$this->table;
    $id = $this->db->query($sql)->row_array();
    return $id['number']+1;
}
}
 
?>